package com.github.ghsea.scheduler.service;

import com.github.ghsea.scheduler.entity.TaskSchedulerEntity;
import com.github.ghsea.scheduler.repository.TaskSchedulerRepository;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author guhai
 * @since 2021/6/17 22:37
 */
@Service
public class TaskSchedulerService {

    @Autowired
    private TaskSchedulerRepository taskSchedulerRepository;

    /**
     * 查询宕机的Scheduler
     *
     * @return
     */
    public TaskSchedulerEntity queryCrashedServer() {
        return taskSchedulerRepository.getCrashedTaskScheduler();
    }

    /**
     * 更新心跳信息
     *
     * @param server
     * @param heartbeatTime
     * @param nextHeartbeatTime
     */
    public void heartbeat(String server, Date heartbeatTime, Date nextHeartbeatTime) {
        TaskSchedulerEntity existTaskScheduler = taskSchedulerRepository.queryHearbeartByServer(server);
        TaskSchedulerEntity taskSchedulerEntity = new TaskSchedulerEntity();
        taskSchedulerEntity.setServer(server);
        taskSchedulerEntity.setHeartbeatTime(heartbeatTime);
        taskSchedulerEntity.setNextHeartbeatTime(nextHeartbeatTime);
        if (existTaskScheduler == null) {
            Date now = new Date();
            taskSchedulerEntity.setStartTime(now);
            taskSchedulerEntity.setCreateTime(now);
            taskSchedulerRepository.insert(taskSchedulerEntity);
        } else {
            taskSchedulerRepository.updateHeatbeatByServer(taskSchedulerEntity);
        }
    }

}
